//
//  HJModifyNicknameController.m
//  KaiChat
//
//  Created by lx on 2023/12/14.
//

#import "HJModifyNicknameController.h"
#import "QMUITextField.h"
#import "QMUIButton.h"
#import "HJMinePresent.h"
#import "HJUserModel.h"
#import "HJIM.h"

@interface HJModifyNicknameController ()<QMUITextFieldDelegate>

@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, weak) QMUITextField *textField;
@property (nonatomic, weak) HJStyle1Button *OKButton;


@end

@implementation HJModifyNicknameController


- (void)showInController:(UIViewController *)controller {
    [controller presentViewController:self animated:NO completion:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    
    
    self.view.backgroundColor = UIColor.clearColor;
    
    UIView *maskView = [[UIView alloc] initWithFrame:self.view.bounds];
    maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [self.view addSubview:maskView];
    
    UIView *contentView = [UIView addToView:maskView];
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.frame = CGRectMake(0, KScreenHeight - 215, KScreenWidth, 215);
    
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:contentView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = contentView.bounds;
    maskLayer.path = bezierPath.CGPath;
    contentView.layer.mask = maskLayer;
    
    UIView *topView = [UIView addToView:contentView];
    topView.backgroundColor = UIColor.whiteColor;
    topView.frame = CGRectMake(0, 0, KScreenWidth, 50);
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(50);
        make.left.right.offset(0);
        make.top.offset(0);
    }];
    
    QMUIButton *closeButton = [QMUIButton addToView:topView];
    [closeButton addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setImage:[UIImage imageNamed:@"nav_close"] forState:UIControlStateNormal];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.width.height.offset(30);
        make.left.offset(leftRightMargin);
    }];
    
    UILabel *titleLabel = [UILabel lableWithSuperView:topView font:UIFontMediumMake(15) color:UIColor.blackColor title:@"Modify your nickname" textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    UIView *textFieldContentView = [UIView addToView:contentView];
    textFieldContentView.addCornerRadius(10);
    textFieldContentView.backgroundColor = UIColor.tj_F6F6F6Color;
    [textFieldContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.equalTo(topView.mas_bottom).offset(leftRightMargin);
        make.height.offset(50);
    }];
    
    QMUITextField *textField = [QMUITextField addToView:textFieldContentView];
    textField.textColor = UIColor.tj_333333Color;
    textField.text = HJUserInfo.nickname;
    textField.font = UIFontMake(14);
    textField.delegate = self;
    textField.maximumTextLength = 20;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    textField.placeholderColor = UIColor.tj_placeholderTextColor;
    textField.placeholder = @"Alphets numbers";
    textField.backgroundColor = UIColor.tj_F6F6F6Color;
    textField.tintColor = UIColor.tj_mainColor;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.right.inset(10);
        make.top.bottom.offset(0);
    }];
    
    HJStyle2Button *cancelButton = [HJStyle2Button buttonWithSuperView:contentView font:UIFontMediumMake(14) color:nil title:@"Cancel"];
    [cancelButton addTarget:self action:@selector(didClickCancelButton) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.inset(leftRightMargin);
        make.right.equalTo(self.view.mas_centerX).inset(12);
        make.height.offset(55);
        make.bottom.inset(20);
    }];
    
    HJStyle1Button *OKButton = [HJStyle1Button buttonWithSuperView:contentView font:UIFontMediumMake(14) color:nil title:@"OK"];
    OKButton.enabled = NO;
    [OKButton addTarget:self action:@selector(didClickOKButton) forControlEvents:UIControlEventTouchUpInside];
    [OKButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(cancelButton);
        make.right.inset(leftRightMargin);
        make.left.equalTo(self.view.mas_centerX).inset(12);
        make.bottom.equalTo(cancelButton);
    }];
    
    _textField = textField;
    _maskView = maskView;
    _contentView = contentView;
    _OKButton = OKButton;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlerKeyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlerKeyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    dispatch_async_main_queue(^{
        [self.textField becomeFirstResponder];
    });
}

- (void)didClickDismissButton {
    [self.textField resignFirstResponder];
}

- (void)didClickCancelButton {
    [self.textField resignFirstResponder];
}

- (void)didClickOKButton {
    NSString *nickname = _textField.text;
    [HJMinePresent modifyNickname:nickname complete:^(NSError * _Nullable error) {
        if (error) {
            [HJHUD showErrorMessage:@"Operation failed"];
            return;
        }
        
        dispatch_async_sql_queue(^{
            HJChatUserModel *chatUserModel = [HJIM.shareIM.userManager queryUserInfoByUserId:HJUserInfo.userId];
            chatUserModel.nickname = nickname;
            [chatUserModel bg_saveOrUpdate];
            dispatch_async_main_queue(^{
                [[NSNotificationCenter defaultCenter] postNotificationName:userInfoChangeNotification object:chatUserModel];
            });
        });
        
        HJUserModel *userModel = [HJUserModel currentAccountModel];
        userModel.nickname = nickname;
        [userModel bg_saveOrUpdateAsync:nil];
        
        HJUserInfo.nickname = nickname;
        if (self.complete) {
            self.complete();
        }
        [self.textField resignFirstResponder];
        [HJHUD showSucceedMessage:@"Successful operation"];
    }];
}

- (void)handlerKeyboardWillShowNotification:(NSNotification *)noti {
    
    if (!self.textField.isFirstResponder) {
        return;
    }
    
    _contentView.hidden = NO;
    
    NSDictionary *userInfo = [noti userInfo];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGFloat height = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        CGRect rect = self.contentView.frame;
        rect.origin.y = KScreenHeight- (self.contentView.frame.size.height + height);
        self.contentView.frame = rect;
        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    }];
}

- (void)handlerKeyboardWillHideNotification:(NSNotification *)noti {
    
    if (!self.textField.isFirstResponder) {
        return;
    }
    
    NSDictionary *userInfo = [noti userInfo];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];//动画曲线类型
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        CGRect rect = self.contentView.frame;
        rect.origin.y = KScreenHeight;
        self.contentView.frame = rect;
        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    } completion:^(BOOL finished) {
        [IQKeyboardManager sharedManager].enable = YES;
        [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    // 检查是否以空格开头或结尾
    if ([newText hasPrefix:@" "] || [newText hasSuffix:@" "]) {
        return NO; // 不允许输入空格
    }
    // 允许输入其他字符
    return YES;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    _OKButton.enabled = textField.text.length > 0;
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationCustom;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}




@end
